package com.htbb.base.handler;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;

import com.htbb.base.cache.CacheService;
import com.htbb.base.enums.LoginEnum;
import com.htbb.base.exception.ErrorCodeException;
import com.htbb.base.util.Token;
import com.htbb.model.User;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class TokenHandler {

	private static final Logger LOGGER = Logger.getLogger(TokenHandler.class);

	@Autowired
	private CacheService cacheService;

	@ModelAttribute
	public User getUser(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "token", required = false) String token) {
		LOGGER.debug("TokenHandler getUser -----------------------token: " + token);
		String path = request.getRequestURL().toString();
		boolean needAuth = path.contains("/au/");
		if (!needAuth) {
			return null;
		}
		if (StringUtils.isBlank(token)) {
			token = request.getHeader("token");
		}
		if (StringUtils.isBlank(token) && request.getCookies() != null) {
			for (Cookie cookie : request.getCookies()) {
				String cookieStr = ReflectionToStringBuilder.toString(cookie);
				LOGGER.debug("TokenHandler--------------cookie:" + cookieStr);
				if (cookie.getName().equalsIgnoreCase("token")) {
					token = cookie.getValue();
					break;
				}
			}
		}
		if (needAuth && StringUtils.isBlank(token)) {
			throw new ErrorCodeException(2000, "The token is missing or expired!");
		}
		Map<String, Object> map = Token.isTokenStringValid(token, cacheService);
		if(map == null){
			throw new ErrorCodeException(2000, "未登录，请先登录！");
		}
		Long time = (Long) map.get("time");
		long now = System.currentTimeMillis();
		long t = now - time;
		if (t > LoginEnum.ONE_DAY) { // 登录时间大于一天
			Cookie cookie = new Cookie("token", null);
			cookie.setMaxAge(0);
			cookie.setDomain(LoginEnum.DOMAIN);
			cookie.setPath("/");
			response.addCookie(cookie);
			throw new ErrorCodeException(2000, "未登录，请先登录！");
		}
		User user = (User) map.get("user");
		return user;
	}
}
